package cn.yuanqiao.archive.wenjianzhengli.utils;

import cn.yuanqiao.common.utils.sign.Base64;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

@Component
public class OcrUtils {


    public boolean imageToOFD(File file, String ofdPath, String pictureUrl) throws IOException {
        try {
            File ofdFile = new File(ofdPath);
            if (!new File(ofdPath).getParentFile().exists()) {
                new File(ofdPath).getParentFile().mkdirs();
            }
            MultiValueMap<String, Object> params = new LinkedMultiValueMap();
            params.add("base64img", fileToBase64(file.getAbsolutePath()));
            params.add("outputType", "ofd");
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
            //  执行HTTP请求
            ResponseEntity<com.alibaba.fastjson.JSONObject> buffer = restTemplate.exchange(pictureUrl, HttpMethod.POST, requestEntity, com.alibaba.fastjson.JSONObject.class);
            com.alibaba.fastjson.JSONObject json=buffer.getBody();
            if (json.getString("code").equals("0")) {
                //获取base64
                String base64 = json.getJSONObject("data").getString("buffer");
                string2File(base64, ofdPath);
            }
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    public boolean officeToOFD(File file, String ofdPath, String ofdUrl) {
        try {
            File ofdFile = new File(ofdPath);
            if(!ofdFile.exists()) {
                if (!new File(ofdPath).getParentFile().exists()) {
                    new File(ofdPath).getParentFile().mkdirs();
                }
                ofdFile.createNewFile();

            }
            MultiValueMap<String, Object> params = new LinkedMultiValueMap();
            FileSystemResource resource = new FileSystemResource(file);
            params.add("file", resource);
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
            //  执行HTTP请求
            // 使用 exchange 方法发送 GET 请求并处理响应   client.exchange(url, HttpMethod.POST, requestEntity, byte[].class);
            ResponseEntity<ByteArrayResource> responseEntity = client.exchange(ofdUrl, HttpMethod.POST, requestEntity, ByteArrayResource.class);

            // 检查响应状态码
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                // 获取响应体中的 InputStream
                if (responseEntity.getBody() != null) {
                    InputStream inputStream = responseEntity.getBody().getInputStream();

                    // 写入到本地文件
                    try (FileOutputStream outputStream = new FileOutputStream(ofdPath)) { // 替换为你的文件名和扩展名
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        // 确保关闭 InputStream
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                } else {
                    // 处理错误响应
                    System.err.println("Failed to download file: " + responseEntity.getStatusCode());
                    return false;
                }
            }else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
        return true;
    }

/*
    public void tifToOfd(String filePath,String pictureUrl,String tifPath, Long docId,String hz) {
       try {
           //需要将多页tif，tiff文件分隔识别然后合成一个ofd
           //分割tif文件
           File tifFile = new File(filePath);
           String value = tifUtil.makeSingleTif(tifFile, docId.toString(), tifPath, hz);
           String splitPath = value.split(";")[0];
           int num = Integer.valueOf(value.split(";")[1]);
           String fileName = tifFile.getName();
           //拆分文件
           String splitOfdPath=splitPath + File.separator+"ofd";
           File splitOfdFile=new File(splitOfdPath);
           if(!splitOfdFile.exists()){
               splitOfdFile.createNewFile();
           }
           MultiValueMap<String, Object> params = new LinkedMultiValueMap();
           params.add("outputType", "ofd");
           RestTemplate restTemplate = new RestTemplate();

           int j = 1;
           for (int i = 0; i < num; i++) {
               File tif = new File(splitPath + File.separator
                       + String.format(fileName.substring(0, fileName.lastIndexOf(".")) + "-" + j++) + "." + hz);
               //调用接口然后生成一个个的ofd
               params.add("file", tif);
               JSONObject json = restTemplate.postForObject(pictureUrl, params, JSONObject.class);
               if (json.getString("code").equals("0")) {
                   //获取base64
                   String path=splitOfdPath+File.separator +
                           String.format(fileName.substring(0, fileName.lastIndexOf(" .")) + "-" + j++) + ".ofd";
                   String base64 = json.getJSONObject("data").getString("buffer");
                   string2File(base64, path);
               }

           }
           //转成ofd



       }catch (Exception ex){
           ex.getMessage();
       }


    }
*/

    public  void string2File(String str, String target) throws Exception {
        Base64 b64 = new Base64();
        byte[] buffer = b64.decode(str);
        FileOutputStream fos = new FileOutputStream(target);
        fos.write(buffer);
        fos.close();
    }

    //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
    public  String fileToBase64(String imgFile){
        if (imgFile == null) {
            return null;
        }
        try {
            byte[] b = Files.readAllBytes(Paths.get(imgFile));
            return java.util.Base64.getEncoder().encodeToString(b);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }
    public static void main(String[] args) {
        File decDir=new File("D:/ocr");
        File[] decDirs = decDir.listFiles();
        Arrays.sort(decDirs);
        for (File file:decDirs){
            System.out.println("f"+file.getName());
        }
    }

    public boolean imageToPDF(File file, String pdfPath, String pictureUrl) {
        try {
            File pdfFile = new File(pdfPath);
            if (!new File(pdfPath).getParentFile().exists()) {
                new File(pdfPath).getParentFile().mkdirs();
            }
            MultiValueMap<String, Object> params = new LinkedMultiValueMap();
            params.add("base64img", fileToBase64(file.getAbsolutePath()));
            params.add("outputType", "pdf");
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(params, headers);
            //  执行HTTP请求
            ResponseEntity<com.alibaba.fastjson.JSONObject> buffer = restTemplate.exchange(pictureUrl, HttpMethod.POST, requestEntity, com.alibaba.fastjson.JSONObject.class);
            JSONObject json=buffer.getBody();
            if (json.getString("code").equals("0")) {
                //获取base64
                String base64 = json.getJSONObject("data").getString("buffer");
                string2File(base64, pdfPath);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

